package com.caixin.infrastructure.repository.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.caixin.infrastructure.dataobject.user.entity.UserDO;
import com.caixin.infrastructure.dataobject.user.mapper.UserDoMapper;
import com.caixin.infrastructure.repository.user.convert.UserConvert;
import com.caixin.domain.user.agg.User;
import com.caixin.domain.user.repository.UserRepo;
import com.caixin.domain.user.types.unique.UserId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


/**
 * 系统用户RepoImpl
 *
 * @author caixin
 * @version 1.0.0
 * @date 2021年12月11日 10:14
 */
@Service
@Slf4j
public class UserRepoImpl implements UserRepo {

    @Resource
    private UserConvert userConvert;
    @Resource
    private UserDoMapper userDoMapper;

    /**
     * 保存
     *
     * @param user:
     * @return void
     * @date 2021年12月11日 10:16
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(User user) {
        //保存用户信息
        UserDO userDO = userConvert.toUserDO(user);
        userDoMapper.insert(userDO);
        log.info("保存成功！");
    }

    @Override
    public User find(UserId userId) {
        Long id = (Long) userId.getValue();
        UserDO userDO = userDoMapper.selectById(id);
        return userConvert.userFormat(userDO);
    }

    @Override
    public User findAll() {
        return null;
    }

    @Override
    public void delete(UserId userId) {

    }

    /**
     * 根据用户名查询
     *
     * @param userName
     * @return com.domain.user.agg.User
     * @date 2021/11/19 10:31
     */
    @Override
    public User findUserByName(String userName) {
        LambdaQueryWrapper<UserDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserDO::getUserName, userName);
        lambdaQueryWrapper.last("limit 1");
        UserDO userDO = userDoMapper.selectOne(lambdaQueryWrapper);
        return userConvert.userFormat(userDO);
    }
}
